package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.CountDownLatch;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class MultiThread {
	BufferedReader br;
	private static SAXReader reader = new SAXReader();
	int i = 0;

	public static void main(String[] args) throws Exception {

		new MultiThread().go();
	}

	public void go() throws Exception {
		File file = new File("user/default/1276856037500");
		FileReader fr = new FileReader(file);
		br = new BufferedReader(fr);

		System.out.println("start:" + System.currentTimeMillis());
		long before = System.currentTimeMillis();
		/* start */
		int threadNum = 10;
		final CountDownLatch cd = new CountDownLatch(threadNum);
		Runnable r = new Task(this, cd);
		for (int i = 0; i < threadNum; i++) {
			new Thread(r).start();
		}
		cd.await();
		/* end */
		long after = System.currentTimeMillis();
		System.out.println((after - before));
	}

	public synchronized String getLine() throws Exception {
		if (i == 1000) {
			return null;
		} else {
			i++;
			return br.readLine();
		}
	}

	public synchronized Document read(BufferedReader br) throws Exception {
		return reader.read(br);

	}
}

class Task implements Runnable {
	MultiThread m;
	CountDownLatch cd;
	private final static String URLTemp = "http://dict.cn/ws.php?q=";

	public Task(MultiThread m, CountDownLatch cd) {
		this.m = m;
		this.cd = cd;
	}

	@Override
	public void run() {
		String s = null;
		while (true) {
			try {
				s = m.getLine();
				if (s == null) {
					break;
				}

				checkWord(s);

			} catch (Exception e) {
				System.out.println("word:" + s);
				e.printStackTrace();
			}
		}
		cd.countDown();
	}

	public boolean checkWord(String word) throws Exception {

		InputStream is = new URL(URLTemp + URLEncoder.encode(word))
				.openStream();
		InputStreamReader isr = new InputStreamReader(is, "GBK");
		BufferedReader br = new BufferedReader(isr);
		// 同步
		Document doc = m.read(br);
		Element root = doc.getRootElement();
		for (Object o : root.elements()) {
			Element e = (Element) o;
			if (e.getName().equals("def")
					&& e.getTextTrim().equals("Not Found")) {
				return false;

			}
		}
		return true;
	}

}